package com.wsc.crawler.grabber;
 

import java.util.AbstractList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import com.wsc.crawler.URLutils.URLBean;

/**
 *
 * @author madhu
 */
public class URLBeanQueue {
	private LinkedList<URLBean> list;
	
	// URLQueue constructor
	public URLBeanQueue()
	{
		// Create a new LinkedList.
		list = new LinkedList<URLBean>();
	}

	public URLBeanQueue(LinkedList<URLBean> q)
	{
 		this.list =q;
	}

	public boolean isEmpty()
	// Post: Returns true if the queue is empty. Otherwise, false.
	{
		return list.isEmpty();
	}

	public void enqueue(URLBean bean)
	// Post: An item is added to the back of the queue.
	{
		// Append the item to the end of our linked list.
		list.add(bean);
	}

	public URLBean dequeue()
	{
		if(!list.isEmpty()){
		URLBean bean = list.poll();
		//list.removeFirst();
		// Return the item
		return bean;
                }
       return null;
	}

	public URLBean peek()
	{
		// This method is very similar to dequeue(). but without removing item
		// See URLQueue.dequeue() for comments.
		return list.peek();
	}
        
   public void printQueue(URLBeanQueue urlqueue) {
        System.out.println(list);
       }

   public int size() {
        return list.size();
    }

   public void clear() {
        list.clear();
    }

   public boolean hasThis(String tobefetched) {
        // if this function returns true means that the url tobefetchd is already fetched
       return list.contains(tobefetched);
    }
   
   /*
    *  getSubQueue method Returns a sub URLQueue by splitting the queue, by startIndex and endIndex.
    */
   
   public URLBeanQueue getSubQueue(int startIndex, int endIndex){
	  
	    
	   LinkedList<URLBean> l= new LinkedList<URLBean>(((AbstractList<URLBean>) list).subList(startIndex, endIndex));
	   //  System.out.println(l.toString());
		  	  return new URLBeanQueue(l);   
	   
		   
   }
   
   public void setQueue(List<URLBean> beanlist){
	this.list = (LinkedList<URLBean>) beanlist;   
   }
   
   public String toString(){
	   
	Iterator<URLBean> itr= list.iterator();
	StringBuffer sb=new StringBuffer();
	sb.append("{");
	while(itr.hasNext()){
	  sb.append("[");
	  sb.append("\""+itr.next().getOriginalURL()+"\",");
	  sb.append("\""+itr.next().getDnsresolvedHost()+"\",");
	  sb.append("\""+itr.next().getMessage()+"\"");
	  sb.append("]");
	}
	sb.append("}");
	
	return sb.toString();
	   
   }

public URLBean getURLBeanAt(int i) {
 // list size should be greater than i 
	if(list.size() > 0 & list.size() > i)
	return list.get(i);
	else return null;
}
}